package com.basejace.system.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.basejace.common.model.PubRole;
import com.basejace.core.base.BaseController;
import com.basejace.core.model.PageBootstrapTable;
import com.basejace.core.sequence.Sequence;
import com.jfinal.json.FastJsonFactory;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class RoleController extends BaseController {

	public RoleController() {
		setModelClass(PubRole.class);
	}
	
	public void list() {
		String rolename = getPara("rolename");
		String sqlExceptSelect = "from pub_role where 1=1 ";
		List sqlCondition = new ArrayList();
		if (StrKit.notBlank(rolename)) {
			sqlExceptSelect += "and rolename like ? ";
			sqlCondition.add("%" + rolename + "%");
		}
		
		int offset = getParaToInt("offset");
		int limit = getParaToInt("limit");
		int pageNumber = (offset) / limit + 1;
		
		Page<Record> page = Db.paginate(pageNumber, limit, "select * ", sqlExceptSelect , sqlCondition.toArray());
		
		List<Record> list = page.getList();
		List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Record object = (Record) iterator.next();
			rows.add(object.getColumns());
		}
		
		PageBootstrapTable p = new PageBootstrapTable();
		p.setTotal(page.getTotalRow());
		p.setPageSize(page.getPageSize());
		p.setPageNumber(page.getPageNumber());
		p.setRows(rows);
		log.info(FastJsonFactory.me().getJson().toJson(p).toString());
		
		renderJson(p);
	}
	
	public void beforeSave() throws Exception {
		this.getModelEntity().set("roleid", Sequence.getSequence());
	}
}
